package config

import (
	"Hypnos-Soundcore/components/feishu"
	"Hypnos-Soundcore/components/logging"
	"Hypnos-Soundcore/components/redisCluster"
	"Hypnos-Soundcore/components/trafficcontrol"
	"Hypnos-Soundcore/constants"
	"errors"
	"strings"
)

// Verify interface
type Verify interface {
	verify() error
}

// GinConfig gin config
type GinConfig struct {
	Mode                           string            // 运行模式
	JiraUseHttps                   bool              `json:"jira_use_https" yaml:"jira_use_https"` // jira使用https
	IosVoips2Apns                  bool              `json:"ios_voip2apns" yaml:"ios_voip2apns"`   // 请求是否使用RSA加密
	PressTest                      bool              `json:"press_test" yaml:"press_test"`         // 是不是压测环境
	RSARequest                     bool              `json:"rsa_request" yaml:"rsa_request"`       // 请求是否使用RSA加密
	AesEncrypt                     bool              `json:"aes_encrypt" yaml:"aes_encrypt"`       // 请求是否使用AES加密
	Pprof                          bool              `json:"pprof" yaml:"pprof"`                   // 是否开启pprof
	LogUserOp                      bool              `json:"log_user_op" yaml:"log_user_op"`       // 是否保存用户操作记录
	ShortIdPoolSize                int               `json:"short_id_pool_size" yaml:"short_id_pool_size"`
	ShortIdPoolMinSize             int               `json:"short_id_pool_min_size" yaml:"short_id_pool_min_size"`
	ShortKeyCacheTime              int               `json:"short_key_cache_time" yaml:"short_key_cache_time"`
	AbMode                         string            `json:"ab_mode" yaml:"ab_mode"`                                       // ABTest的模式
	ReloadHost                     string            `json:"reload_host" yaml:"reload_host"`                               // etcd host
	ReloadKey                      string            `json:"reload_key" yaml:"reload_key"`                                 // etcd key
	ShortUrlHost                   string            `json:"shorturl_host" yaml:"shorturl_host"`                           // short url host
	Templates                      string            `json:"templates" yaml:"templates"`                                   // html path
	CheckVoltageVersion            string            `json:"check_voltage_version" yaml:"check_voltage_version"`           // 电压检查的版本
	PushAppVersionAndroid          string            `json:"push_app_version_android" yaml:"push_app_version_android"`     // 电压检查的版本
	PushAppVersionIOS              string            `json:"push_app_version_ios" yaml:"push_app_version_ios"`             // 电压检查的版本
	FirebaseIOSConfPath            string            `json:"firebase_conf_path_ios" yaml:"firebase_conf_path_ios"`         // firebase config path
	FirebaseAndroidConfPath        string            `json:"firebase_conf_path_android" yaml:"firebase_conf_path_android"` // firebase config path
	ApnsVoipCert                   string            `json:"apns_voip_cert" yaml:"apns_voip_cert"`                         // apns voip cert
	ApnsVoipPassword               string            `json:"apns_voip_password" yaml:"apns_voip_password"`                 // apns voip password
	ApnsNormalCert                 string            `json:"apns_normal_cert" yaml:"apns_normal_cert"`                     // apns normal cert
	ApnsNormalPassword             string            `json:"apns_normal_password" yaml:"apns_normal_password"`             // apns normal password
	ApnsJWTAuthFile                string            `json:"apns_jwt_auth_file" yaml:"apns_jwt_auth_file"`                 // apns jwt auth file
	ApnsJWTTeamID                  string            `json:"apns_jwt_team_id" yaml:"apns_jwt_team_id"`                     // apns jwt team id
	ApnsJWTKeyID                   string            `json:"apns_jwt_key_id" yaml:"apns_jwt_key_id"`                       // apns jwt key id
	ApnsJWTBundleID                string            `json:"apns_jwt_bundle_id" yaml:"apns_jwt_bundle_id"`                 // apns jwt bundle id
	AppEnv                         string            `json:"app_env" yaml:"app_env"`                                       // app 的运行环境
	StreamIgnoreInterval           int               `json:"stream_ignore_interval" yaml:"stream_ignore_interval"`         // stream开始停止忽略的时间差
	ServerEnv                      string            `json:"server_env" yaml:"server_env"`                                 //标示服务器环境
	CbcKey                         string            `json:"cbc_key" yaml:"cbc_key"`
	DecryptKeys                    map[string]string `json:"decrypt_keys" yaml:"decrypt_keys"`                 //已使用的全部解密方式
	CurrentEncryptType             string            `json:"current_encrypt_type" yaml:"current_encrypt_type"` //当前使用的加密方式【"0001"】
	DeviceAccessTokenExpireIn      int               `json:"device_access_token_expire_in" yaml:"device_access_token_expire_in"`
	IosPushMethod                  string            `json:"ios_push_method" yaml:"ios_push_method"`
	EnableMotionPushNotify         bool              `json:"enable_motion_push_notify" yaml:"enable_motion_push_notify"`
	EnableRegisterPushTokenAclMqtt string            `json:"enable_register_push_token_acl_mqtt" yaml:"enable_register_push_token_acl_mqtt"`
	ReadDeviceFromOldRedis         bool              `json:"read_device_from_old_redis" yaml:"read_device_from_old_redis"`
	WriteDeviceFromOldRedis        bool              `json:"write_device_from_old_redis" yaml:"write_device_from_old_redis"`
	DeleteDeviceFromOldRedis       bool              `json:"delete_device_from_old_redis" yaml:"delete_device_from_old_redis"`
	ReadStationFromOldRedis        bool              `json:"read_station_from_old_redis" yaml:"read_station_from_old_redis"`
	WriteStationFromOldRedis       bool              `json:"write_station_from_old_redis" yaml:"write_station_from_old_redis"`
	DeleteStationFromOldRedis      bool              `json:"delete_station_from_old_redis" yaml:"delete_station_from_old_redis"`
}

type AppConfig struct {
	//AppName         string `json:"app_name" yaml:"app_name"`                     // app name
	//PackageName     string `json:"package_name" yaml:"package_name"`             // package
	//ApnsJWTBundleID string `json:"apns_jwt_bundle_id" yaml:"apns_jwt_bundle_id"` // apns jwt bundle id
}

// SwaggerConfig swagger config
type SwaggerConfig struct {
	Enable  bool   `json:"sw_enable" yaml:"sw_enable"` // 是否支持swagger
	UIPath  string `json:"ui_path" yaml:"ui_path"`     // UI路径
	APIPath string `json:"api_path" yaml:"api_path"`   // 接口定义路径
}

// LogConfig log config
type LogConfig struct {
	ToFile    bool   `json:"to_file" yaml:"to_file"`       // 是否写日志文件
	LevelName string `json:"level_name" yaml:"level_name"` // 日志级别
	FileName  string `json:"file_name" yaml:"file_name"`   // 日志文件名
}

type DynamicLink struct {
	ApiKey          string `json:"api_key" yaml:"api_key"`         // 获取s3文件的apiKey
	Url             string `json:"url" yaml:"url"`                 // 获取s3文件的API链接
	DomainUriPrefix string `json:"url" yaml:"domain_uri_prefix"`   // 获取s3文件的域名
	StorageUrl      string `json:"storage_url" yaml:"storage_url"` // 获取s3文件的域名
}

// NetworkConfig network config
type NetworkConfig struct {
	ListenPort string `json:"listen_port" yaml:"listen_port"` // 监听端口号
	UseHTTPS   bool   `json:"use_https" yaml:"use_https"`     // 是否https
	CertFile   string `json:"cert_file" yaml:"cert_file"`     // 证书文件
	KeyFile    string `json:"key_file" yaml:"key_file"`       // 密钥文件
	HealthPort string `json:"health_port" yaml:"health_port"` // 健康检测端口号
}

func (netConf *NetworkConfig) verify() error {
	var err error
	if netConf.UseHTTPS && (len(netConf.CertFile) == 0 || len(netConf.KeyFile) == 0) {
		err = errors.New("https require cert and key file")
	}
	return err
}

// DbConfig db config for mysql
type DbConfig struct {
	MaxIdleConns    int     `json:"max_idle_conns" yaml:"max_idle_conns"`         // 最大闲置连接数
	MaxOpenConns    int     `json:"max_open_conns" yaml:"max_open_conns"`         // 最大打开连接数
	ConnMaxLifeTime int     `json:"conn_max_life_time" yaml:"conn_max_life_time"` // 连接生命周期(秒)
	DbConf          string  `json:"db_config" yaml:"db_config"`                   // 数据库连接配置
	ShardRange      []int64 `json:"shard_range" yaml:"shard_range"`               // 分片user_range_id段
}

// MysqlConfig mysql config
type MysqlConfig struct {
	Debug bool // 打印调试信息
	// 是否使用snowflake生成id
	SnowFlakeID bool
	// snowflakeid的模值
	SnowFlakeMod int64
	// 是否使用64位id
	GenerateInt64ID bool
	// 拆分数据库过渡版本
	// v1: 写入/更新/删除时除操作默认数据库，同时也要操作代理数据库
	// v2: 读取时若不是根据id查询，则需要做去重动作
	Sharding string
	// 分库名称数组
	DBShards []string
	Dbs      map[string]DbConfig // 数据库连接配置
}

func (mysqlConf MysqlConfig) verify() error {
	var err error
	if len(mysqlConf.Dbs) == 0 {
		err = errors.New("mysql config is invalid")
		return err
	}
	for _, name := range constants.DBNames {
		if _, ok := mysqlConf.Dbs[name]; !ok {
			err = errors.New(name + " db source is not defined")
			break
		}
	}
	return err
}

// WebInfo .
type WebInfo struct {
	WebPath string `json:"web_path" yaml:"web_path"` // web地址
	DirPath string `json:"dir_path" yaml:"dir_path"` // 文件路径
}

// BuiltInConfig .
type BuiltInConfig struct {
	Webs map[string]string
}

// QueueInfo .
type QueueInfo struct {
	Name    string // 队列名称
	Worker  int    // 最小协程数
	Maximum int    // 最大协程数
}

// QueueConfig .
type QueueConfig map[string]QueueInfo

// CronInfo .
type CronInfo struct {
	Spec            string // 定时设置
	Expired         int    // 过期时间(秒)
	Interval        int    // 间隔时间(秒)
	Limit           int    // 限制个数
	Sleep           int    // 休眠时间(毫秒)
	Worker          int    // 协程数
	PreExpired      int    `json:"pre_expired" yaml:"pre_expired"`             // 提前过期时间(秒)
	ClearEventLimit int    `json:"clear_event_limit" yaml:"clear_event_limit"` // 限制删除event条数

}

// GetSpec .
func (c *CronInfo) GetSpec() string {
	return c.Spec
}

// GetExpired .
func (c *CronInfo) GetExpired() int {
	return c.Expired
}

// GetInterval .
func (c *CronInfo) GetInterval() int {
	return c.Interval
}

// GetSleep .
func (c *CronInfo) GetSleep() int {
	return c.Sleep
}

// GetLimit .
func (c *CronInfo) GetLimit() int {
	return c.Limit
}

// GetWorker .
func (c *CronInfo) GetWorker() int {
	return c.Worker
}

// GetPreExpired .
func (c *CronInfo) GetPreExpired() int {
	return c.PreExpired
}

// GetClearEventLimit .
func (c *CronInfo) GetClearEventLimit() int {
	return c.ClearEventLimit
}

// CronConfig .
type CronConfig map[string]CronInfo

// CallerInfo .
type CallerInfo struct {
	Caller    string `json:"caller" yaml:"caller"`
	SecretKey string `json:"secret_key" yaml:"secret_key"`
}

// CallerConfig .
type CallerConfig []CallerInfo

// AuthConfig .
type AuthConfig struct {
	// 会话类型
	Type string `json:"type" yaml:"type"`
	// 上下文key
	ContextKey string `json:"context_key" yaml:"context_key"`
	// 会话名称
	SessionName string `json:"session_name" yaml:"session_name"`
	// redis前缀
	PrefixKey string `json:"prefix_key" yaml:"prefix_key"`
	// redis地址
	RedisURL string `json:"redis_url" yaml:"redis_url"`
	// redis密钥
	Password string `json:"password" yaml:"password"`
	// 有效时间(秒)
	MaxAge int `json:"max_age" yaml:"max_age"`
}

// UdcConfig .
type UdcConfig struct {
	Bench   bool   `json:"bench" yaml:"bench"`
	Host    string `json:"host" yaml:"host"`
	Timeout int64  `json:"timeout" yaml:"timeout"`
}

// SmartPlatformConfig .
type SmartPlatformConfig struct {
	ClientID          string `json:"client_id" yaml:"client_id"`
	AlexaClientID     string `json:"alexa_client_id" yaml:"alexa_client_id"`
	AlexaClientSecret string `json:"alexa_client_secret" yaml:"alexa_client_secret"`
}

// SmartRpcWorkerConfig
type SmartRpcWorkerConfig struct {
	UsPort   string `yaml:"us_port" json:"us_port"`
	EuPort   string `yaml:"eu_port" json:"eu_port"`
	UsDomain string `yaml:"us_domain" json:"us_domain"`
	EuDomain string `yaml:"eu_domain" json:"eu_domain"`
}

type AliyunConfig struct {
	AccessKeyId                 string `json:"access_key_id" yaml:"access_key_id"`
	SecretKey                   string `json:"secret_key" yaml:"secret_key"`
	RegionId                    string `json:"region_id" yaml:"region_id"`
	VerifyDefaultTemplateCode   string `json:"verify_default_template_code" yaml:"verify_default_template_code"`
	VerifyDefaultTemplateParam  string `json:"verify_default_template_param" yaml:"verify_default_template_param"`
	VerifyDefaultSignName       string `json:"verify_default_sign_name" yaml:"verify_default_sign_name"`
	CnVerifyDefaultTemplateCode string `json:"cn_verify_default_template_code" yaml:"cn_verify_default_template_code"`
}

type Sms struct {
	DefaultChannel  int      `json:"default_channel" yaml:"default_channel"`
	SmsChannel      []int    `json:"sms_channel" yaml:"sms_channel"`
	SendModel       int      `json:"send_model" yaml:"send_model"`
	MaxSend         int      `json:"max_send" yaml:"max_send"`
	VerifyExpire    int      `json:"verify_expire" yaml:"verify_expire"`
	IgnorePhoneCode []string `json:"ignore_phone_code" yaml:"ignore_phone_code"`
	NoticeUrl       []string `json:"notice_url" yaml:"notice_url"`
}

type AwsSms struct {
	AccessKey         string `json:"access_key" yaml:"access_key"`
	SecretKey         string `json:"secret_key" yaml:"secret_key"`
	Region            string `json:"region" yaml:"region"`
	AppId             string `json:"app_id" yaml:"app_id"`
	OriginationNumber string `json:"origination_number" yaml:"origination_number"`
	SenderId          string `json:"sender_id" yaml:"sender_id"`
	RegisteredKeyword string `json:"registered_keyword" yaml:"registered_keyword"`
}

type Cmi struct {
	Url            string `json:"url" yaml:"url"`
	AuthKey        string `json:"auth_key" yaml:"auth_key"`
	DefaultChannel int    `json:"default_channel" yaml:"default_channel"`
	SendChannel    []int  `json:"send_channel" yaml:"send_channel"`
}

type Blacklist struct {
	PerTime         int      `json:"per_time" yaml:"per_time"`
	Total           int      `json:"total" yaml:"total"`
	BlacklistUserId []string `json:"blacklist_user_id" yaml:"blacklist_user_id"`
	BlacklistEmail  []string `json:"blacklist_email" yaml:"blacklist_email"`
}

// ControllerConfig 业务相关配置
type ControllerConfig struct {
	DoorSensorHisrotyReserveDays int `json:"door_sensor_history_reserve_days" yaml:"door_sensor_history_reserve_days"`
}

// smartLockConfig
type SmartLockConfig struct {
	SessionExpire         int64 `json:"session_expire" yaml:"session_expire"`
	CheckRepeatedTime     int64 `json:"check_repeated_time" yaml:"check_repeated_time"`
	WakeupWaitingTime     int   `json:"wakeup_waiting_time" yaml:"wakeup_waiting_time"`
	TryOpenSessionTime    int   `json:"try_open_session_time" yaml:"try_open_session_time"`
	IsOpenDeviceEncrypted bool  `json:"is_open_device_encrypted" yaml:"is_open_device_encrypted"`
	IsOpenWakeUp          bool  `json:"is_open_wake_up"  yaml:"is_open_wake_up"`
	IsUsePin              bool  `json:"is_use_pin" yaml:"is_use_pin"`
}

type RateLimitingInfo struct {
	LimitType int `json:"limit_type" yaml:"limit_type"`
	Seconds   int `json:"seconds" yaml:"seconds"`
	Limit     int `json:"limit" yaml:"limit"`
}

type ServerSecret struct {
	PresetServerSecret   *ServerSecretInfo `json:"preset_server_secret"  yaml:"preset_server_secret"`
	ExchangeServerSecret *ServerSecretInfo `json:"exchange_server_secret"  yaml:"exchange_server_secret"`
}

type ServerSecretInfo struct {
	PublicKey string `json:"public_key" yaml:"public_key"`
	PrivateD  string `json:"private_d" yaml:"private_d"`
}

type CaptchaInfo struct {
	SynchronousPath []string `json:"synchronous_path" yaml:"synchronous_path"`
}

// IsValid .
func (c *ControllerConfig) IsValid() bool {
	return (c.DoorSensorHisrotyReserveDays > 0)
}

// AutoAlarmSwitch push和emqtt自动报警开关
type AutoAlarmSwitch struct {
	Version   string   `json:"version" yaml:"version"` // 版本号
	Enabled   bool     `json:"enabled" yaml:"enabled"`
	WhiteList []string `json:"white_list" yaml:"white_list"`
}

// BindDeviceCheckCode 绑定设备启用check_code配置
type BindDeviceCheckCode struct {
	DefaultNeedCheckCode bool              `json:"default_need_check_code" yaml:"default_need_check_code"` // 默认需要check_code
	MinStationVersions   map[string]string `json:"min_station_versions" yaml:"min_station_versions"`       // 需要check_code最小基站版本
}

// fundamental服务配置
type FundamentalServerConfig struct {
	Host    string `json:"host" yaml:"host"`       // 服务主机
	Timeout int64  `json:"timeout" yaml:"timeout"` // 请求超时间隔
}

// ServicesBlacklistConfig,服务黑名单配置，BlacklistCountrys:黑名单国家列表
type ServicesBlacklistConfig struct {
	BlacklistCountrys []string `json:"blacklist_countrys" yaml:"blacklist_countrys"`
}

// WakeupFlagConf 定义唤醒标识的配置
type WakeupFlagConf struct {
	WakeupFlag     int     `yaml:"wakeup_flag"`
	DidNumLimit    int     `yaml:"did_num_limit"`
	OrderThreshold int     `yaml:"order_threshold"`
	OrderNum       int     `yaml:"order_num"`
	DidPrefix      string  `yaml:"did_prefix"`
	DidUnitPrice   float64 `yaml:"did_unit_price"`
}

// ProjectConf 定义项目的配置
type ProjectConf struct {
	Project     string           `yaml:"project"`
	CheckSwitch bool             `yaml:"check_switch"`
	DidConfList []WakeupFlagConf `yaml:"wakeup_flag_conf"`
}

// XConfig all config
type XConfig struct {
	Env                          string        `json:"env" yaml:"env"`
	Gin                          GinConfig     // can't hot reload
	Swagger                      SwaggerConfig // can't hot reload
	Log                          LogConfig
	Network                      NetworkConfig        // can't hot reload
	Mysql                        MysqlConfig          // can't hot reload
	Sessions                     []AuthConfig         // can't hot reload
	BuiltIn                      BuiltInConfig        // can't hot reload
	SmartConfig                  SmartPlatformConfig  `json:"smart_platform" yaml:"smart_platform"`
	SmartRpcWorkerConfig         SmartRpcWorkerConfig `yaml:"smart_rpc_worker_config" json:"smart_rpc_worker_config"`
	QueueMaster                  bool                 `json:"queue_master" yaml:"queue_master"`                         // can't hot reload 是否处理异步队列消息，默认true
	QueueMqttChaosHandler        bool                 `json:"queue_mqtt_chaos_handler" yaml:"queue_mqtt_chaos_handler"` // 是否能处理mqtt_chaos消息
	QueueMqttSmartHandler        bool                 `json:"queue_mqtt_smart_handler" yaml:"queue_mqtt_smart_handler"` // 是否能处理mqtt_smart消息
	QueueChaosComand             bool                 `json:"queue_chaos_command" yaml:"queue_chaos_command"`           // 是否能处理后台Command消息
	Queues                       QueueConfig          // can't hot reload
	CronMaster                   bool                 `json:"cron_master" yaml:"cron_master"` // can't hot reload 是否执行定时任务，默认false
	Crons                        CronConfig           // can't hot reload
	Logging                      logging.Config
	Callers                      CallerConfig
	DynamicLinks                 DynamicLink
	MaxLoginNeedCaptcha          int                           `json:"max_login_need_captcha" yaml:"max_login_need_captcha"` //登录需要验证码次数
	MaxLoginError                int                           `json:"max_login_error" yaml:"max_login_error"`               //登录错误最大次数
	MaxLogin                     int                           `json:"max_login" yaml:"max_login"`                           //登录最大次数
	MaxVerifyCodeError           int                           `json:"max_verify_code_error" yaml:"max_verify_code_error"`
	MaxRegister                  int                           `json:"max_register" yaml:"max_register"`
	MaxRegisterNeedCaptcha       int                           `json:"max_register_need_captcha" yaml:"max_register_need_captcha"`
	MaxForgetPassword            int                           `json:"max_forget_password" yaml:"max_forget_password"`
	MaxForgetPasswordNeedCaptcha int                           `json:"max_forget_password_need_captcha" yaml:"max_forget_password_need_captcha"`
	VoiceLanguage                []string                      `json:"voice_language" yaml:"voice_language"` //多语言
	ResetPasswordNoticeUrl       []string                      `json:"reset_password_notice_url" yaml:"reset_password_notice_url"`
	SmartLockConfig              SmartLockConfig               `json:"smart_lock" yaml:"smart_lock"`
	Aliyun                       AliyunConfig                  `json:"aliyun" yaml:"aliyun"`
	Sms                          Sms                           `json:"sms" yaml:"sms"`
	Cmi                          Cmi                           `json:"cmi"  yaml:"cmi"`
	AwsSms                       AwsSms                        `json:"aws_sms" yaml:"aws_sms"`
	IsTestPoolNotify             bool                          `json:"is_test_pool_notify"  yaml:"is_test_pool_notify"`
	TestDaylightType             int                           `json:"test_daylight_type" yaml:"test_daylight_type"`
	PoolNotifyWeek               string                        `json:"pool_notify_week" yaml:"pool_notify_week"`
	Blacklist                    Blacklist                     `json:"blacklist" yaml:"blacklist"`
	RateLimiting                 map[string][]RateLimitingInfo `json:"rate_limiting" yaml:"rate_limiting"`
	Feishu                       feishu.Config                 `json:"feishu" yaml:"feishu"`
	AutoAlarm                    AutoAlarmSwitch               `json:"auto_alarm" yaml:"auto_alarm"`
	ServerSecret                 *ServerSecret                 `json:"server_secret" yaml:"server_secret"`
	Apps                         map[string]AppConfig
	CaptchaInfo                  CaptchaInfo `json:"captcha_info" yaml:"captcha_info"`
	UDC                          UdcConfig
	BindDeviceCheckCode          BindDeviceCheckCode             `json:"bind_device_check_code" yaml:"bind_device_check_code"`
	RedisClusterConfig           redisCluster.RedisClusterConfig `json:"redis_cluster_config"  yaml:"redis_cluster_config"`
	FundamentalServerConfig      FundamentalServerConfig         `json:"fundamental_server_config" yaml:"fundamental_server_config"`
	TrafficWarningPushSwitch     bool                            `json:"traffic_warning_push_switch" yaml:"traffic_warning_push_switch"` //starlight 4G Camera流量预警推送开关
	TrafficControl               trafficcontrol.NacosConfig      `json:"-,optional" yaml:"-"`
	//配置DID监控数据
	DidCheckConf []ProjectConf `json:"did_check_conf" yaml:"did_check_conf"`
}

// GetQueueInfo .
func (xconf *XConfig) GetQueueInfo(name string) (ret *QueueInfo) {
	if xconf.Queues != nil {
		if param, ok := xconf.Queues[name]; ok {
			if !strings.HasSuffix(param.Name, constants.Env) &&
				param.Name[len(param.Name)-1:] == constants.OperatorUnderline {
				param.Name += constants.ProxyName() + constants.OperatorUnderline + constants.EnvName()
			}
			ret = &param
		}
	}
	return
}

// GetCronInfo .
func (xconf *XConfig) GetCronInfo(name string) (ret *CronInfo) {
	if strings.Compare(name, constants.CronLogClear) != 0 { //不是删除日志的定时任务
		// 非删除日志的定时任务则判断是否主服务，非主服务则不执行其它定时任务
		if !xconf.CronMaster {
			return
		}
	}
	if xconf.Crons != nil {
		if param, ok := xconf.Crons[name]; ok {
			ret = &param
		}
	}
	return
}

func (xconf *XConfig) verify() error {
	var err error
	verifies := [...]Verify{&xconf.Mysql, &xconf.Network}
	for _, verify := range verifies {
		err = verify.verify()
		if err != nil {
			break
		}
	}
	return err
}
